package arxiv;

import java.net.*;
import java.util.*;

/*
 * Query.java
 * Logic to create query and call API
 */


public class Query implements Observer {

	// handles to input data and user form
	private KeywordData mySearchData;
	private SearchForm mySearchForm;

	public Query(KeywordData keydata, SearchForm myform) {
		this.mySearchData = keydata;
		this.mySearchForm = myform;
	}

	// on button press in form
	public void update (Observable obj, Object arg) {

		if (mySearchForm.fetchUserInput()) {
            // create URL using search keywords
            String queryString = buildQueryString();
            URL queryURL = buildURL(queryString);
            mySearchForm.displayResults(queryURL);
        }
        else {
            // no search keywords entered
            mySearchForm.displayNoResults();
        }
	}

	// form a string from user input
    public String buildQueryString() {

        // base url
        StringBuilder queryString = new StringBuilder("http://export.arxiv.org/api/query?search_query=");

        // add inserted keywords to query
        queryString.append("all:");
        queryString.append(mySearchData.getKeyText());

        queryString.append("+au:");
        queryString.append(mySearchData.getAuthorText());

        queryString.append("+ti:");
        queryString.append(mySearchData.getTitleText());

        // TODO: error checking on integer number of results
        queryString.append("&start=0&max_results=");
        queryString.append(mySearchData.getNumResultsText());

        return queryString.toString();
    }

    // use URI class to parse String into allowed characters for URL
    public URL buildURL(String queryString) {

        URL queryURL = null;

        try {
            URI queryURI = new URI(queryString);
            // TODO: check which formatting can be done by URI class

            queryURL = queryURI.toURL();
        }
        catch (URISyntaxException e) {
            System.err.println("Problem with URI Syntax : " + queryString);
        }
        catch (MalformedURLException e) {
            System.err.println("Malformed URL : " + queryString);
        }

        return queryURL;
    }


}
